package com.realbrand.net.realbrandpay.ui.activity.wallet.bill;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.adapter.BillAdapter;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.bean.BillBean;
import com.realbrand.net.realbrandpay.inter.IEnumDealRerdList;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.weight.LoadMoreListView;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/10/19.
 */

public class BillActivity extends BaseActivity implements LoadMoreListView.IloadListener {
    @BindView(R.id.bill_listview)
    LoadMoreListView billListview;

    @BindView(R.id.bill_toolbar)
    Toolbar billToolbar;
    List<BillBean> list;
    BillAdapter adapter;
    private boolean isFirst = true;

    private String userName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        billToolbar.setTitle("");
        billToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(billToolbar);
        billToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(BillActivity.this, WalletActivity.class));
                finish();
            }
        });

        SharedPreferences sharedPreferences = getSharedPreferences(Constant.shareName,MODE_PRIVATE);
        userName = sharedPreferences.getString("account", "");
        list = new ArrayList<>();

        //获取账单数据
        getData(userName, list);
        billListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(BillActivity.this, BillDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("billDetail", list.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void getData(final String userName, final List<BillBean> list) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                billRequest(userName, list.size());
            }
        }.start();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.bill_activity;
    }

    @Override
    protected void setOnClick() {

    }

    @Override
    public void onClick(View v) {

    }

    private void billRequest(String ssss, int size) {
        JSONObject json = new JSONObject();
        try {
            json.put("METHOD", "EnumDealRerdList");
            json.put("SOURCE", "BillActivity");
            json.put("CREDENTIALS", "0");
            json.put("TERMINAL", "0");
            json.put("INDEX", Static.getDay());
            json.put("OrderNum", size + "");
            json.put("Month", Static.getMonth());
            json.put("UserAccount", ssss);
            L.d(L.TAG, "月份" + Static.getMonth() + "用户名" + ssss);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, json.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.PAY_BASE_URL).build();
            IEnumDealRerdList iEnumDealRerdList = retrofit.create(IEnumDealRerdList.class);
            Call<ResponseBody> call = iEnumDealRerdList.enumDealRerdList(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                    try {
                        String result = response.body().string();
                        if ("".equals(result)) {
                            Static.toast(BillActivity.this, "网络繁忙");
                        } else {
                            L.d(L.TAG, "账单返回结果" + result);
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                JSONObject objec = jsonObject.getJSONArray("DATA").getJSONObject(0);
                                JSONArray dealType = objec.getJSONArray("DealType");
                                JSONArray tradeTime = objec.getJSONArray("TradeTime");
                                JSONArray userAccount = objec.getJSONArray("EnterpriseName");
                                JSONArray dealNumber = objec.getJSONArray("DealNumber");
                                JSONArray dealMoney = objec.getJSONArray("DealMoney");
                                JSONArray userAvatar = objec.getJSONArray("UserAvatar");
                                for (int i = 0; i < dealType.length(); i++) {
                                    BillBean billBean = new BillBean();
                                    billBean.setDealMoney(String.valueOf(dealMoney.get(i)));
                                    billBean.setDealNumber(String.valueOf(dealNumber.get(i)));
                                    billBean.setDealType(String.valueOf(dealType.get(i)));
                                    billBean.setTradeTime(String.valueOf(tradeTime.get(i)));
                                    billBean.setUserAccount(String.valueOf(userAccount.get(i)));
                                    billBean.setUserAvatar(String.valueOf(userAvatar.get(i)));
                                    list.add(billBean);
                                }
                                if (adapter == null) {
                                    billListview.setInretface(BillActivity.this);
                                    adapter = new BillAdapter(list, BillActivity.this);
                                    billListview.setAdapter(adapter);
                                } else {
                                    adapter.notifyDataSetChanged();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        L.d(L.TAG,e.toString());
                    }
                }


                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLoad() {
        //加载更多数据在此方法
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                billRequest(userName, list.size());
                billListview.loadCompLete();
            }
        }, 2000);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        startActivity(new Intent(this, WalletActivity.class));
        finish();
        return super.onKeyDown(keyCode, event);
    }
}
